package team.nine.kuaichezuche.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import team.nine.kuaichezuche.model.User;
import team.nine.kuaichezuche.repository.UserRepository;
import team.nine.kuaichezuche.service.UserService;
import team.nine.kuaichezuche.service.VerificationCodeService;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserService userService;
    private final VerificationCodeService verificationCodeService;
    private final UserRepository userRepository;

    public AuthController(UserService userService, VerificationCodeService verificationCodeService, UserRepository userRepository) {
        this.userService = userService;
        this.verificationCodeService = verificationCodeService;
        this.userRepository = userRepository;
    }

    /**
     * 用户注册接口
     * 处理前端发送的注册请求，验证参数，检查用户是否已存在，验证验证码，然后创建新用户
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 提取请求参数
            String username = requestBody.get("username") != null ? requestBody.get("username").toString() : "";
            String realName = requestBody.get("realName") != null ? requestBody.get("realName").toString() : "";
            String idCard = requestBody.get("idCard") != null ? requestBody.get("idCard").toString() : "";
            String phoneNumber = requestBody.get("phoneNumber") != null ? requestBody.get("phoneNumber").toString() : "";
            String password = requestBody.get("password") != null ? requestBody.get("password").toString() : "";
            String verificationCode = requestBody.get("verificationCode") != null ? requestBody.get("verificationCode").toString() : "";

            // 验证请求参数
            if (username.isEmpty() || realName.isEmpty() || idCard.isEmpty() || phoneNumber.isEmpty() || password.isEmpty() || verificationCode.isEmpty()) {
                response.put("status", "error");
                response.put("message", "所有字段都是必填项");
                return ResponseEntity.status(400).body(response);
            }

            // 验证验证码
            boolean codeValid = verificationCodeService.verifyCode(phoneNumber, verificationCode);
            if (!codeValid) {
                response.put("status", "error");
                response.put("message", "验证码错误或已过期");
                return ResponseEntity.status(400).body(response);
            }

            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setRealName(realName);
            user.setIdCard(idCard);
            user.setPhone(phoneNumber);
            user.setPassword(password);

            // 调用UserService注册用户
            User registeredUser = userService.registerUser(user);

            // 获取用户令牌（已在register方法中生成并保存）
            String token = registeredUser.getToken();

            // 构造成功响应
            response.put("status", "success");
            response.put("message", "注册成功");
            response.put("token", token);
            response.put("userId", registeredUser.getId());
            response.put("username", registeredUser.getUsername());

            // 返回200成功响应
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("status", "error");
            response.put("message", "注册失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 用户登录接口
     * 处理用户登录请求，验证手机号和密码，返回认证令牌
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 提取请求参数
            String phoneNumber = requestBody.get("phone") != null ? requestBody.get("phone").toString() : "";
            String password = requestBody.get("password") != null ? requestBody.get("password").toString() : "";

            // 验证请求参数
            if (phoneNumber.isEmpty() || password.isEmpty()) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "手机号和密码都是必填项");
                return ResponseEntity.status(400).body(response);
            }

            // 调用UserService验证用户登录
            User user = userService.login(phoneNumber, password);

            // 获取用户令牌（已在login方法中生成并保存）
            String token = user.getToken();

            // 构造成功响应
            response.put("status", "success");
            response.put("code", 2000);
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("userId", user.getId());
            response.put("username", user.getUsername());

            // 返回200成功响应
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("status", "error");
            
            // 根据异常信息返回对应的状态码
            if (e.getMessage().equals("USER_NOT_REGISTERED")) {
                response.put("code", 4001);
                response.put("message", "用户未注册");
                return ResponseEntity.status(400).body(response);
            } else if (e.getMessage().equals("INVALID_PASSWORD")) {
                response.put("code", 4002);
                response.put("message", "密码不正确");
                return ResponseEntity.status(400).body(response);
            } else {
                response.put("code", 5000);
                response.put("message", "登录失败: " + e.getMessage());
                return ResponseEntity.status(500).body(response);
            }
        }
    }
    
    /**
     * 更改密码接口
     * 处理用户更改密码的请求，验证验证码，然后更新密码
     */
    @PostMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 提取请求参数
            String phoneNumber = requestBody.get("phoneNumber") != null ? requestBody.get("phoneNumber").toString() : "";
            String verificationCode = requestBody.get("verificationCode") != null ? requestBody.get("verificationCode").toString() : "";
            String newPassword = requestBody.get("newPassword") != null ? requestBody.get("newPassword").toString() : "";

            // 验证请求参数
            if (phoneNumber.isEmpty() || verificationCode.isEmpty() || newPassword.isEmpty()) {
                response.put("status", "error");
                response.put("message", "所有字段都是必填项");
                return ResponseEntity.status(400).body(response);
            }

            // 调用UserService更改密码
            User user = userService.changePassword(phoneNumber, verificationCode, newPassword);

            // 构造成功响应
            response.put("status", "success");
            response.put("code", 2000);
            response.put("message", "密码更改成功");
            response.put("userId", user.getId());
            response.put("username", user.getUsername());

            // 返回200成功响应
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("status", "error");
            
            // 根据异常信息返回对应的状态码
            if (e.getMessage().equals("4003")) {
                response.put("code", 4003);
                response.put("message", "验证码不正确");
                return ResponseEntity.status(400).body(response);
            } else if (e.getMessage().equals("4001")) {
                response.put("code", 4001);
                response.put("message", "用户未注册");
                return ResponseEntity.status(400).body(response);
            } else {
                response.put("code", 5000);
                response.put("message", "更改密码失败: " + e.getMessage());
                return ResponseEntity.status(500).body(response);
            }
        }
    }

    /**
     * 获取用户信息接口
     * 根据认证令牌获取用户信息
     */
    @GetMapping("/user/info")
    public ResponseEntity<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }

            // 提取令牌内容
            String authToken = token.substring(7);

            // 校验令牌格式并解析时间戳
            String[] tokenParts = authToken.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("status", "error");
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(401).body(response);
            }

            // 解析时间戳并校验是否过期（默认7天）
            long tokenTimestamp;
            try {
                tokenTimestamp = Long.parseLong(tokenParts[4]);
            } catch (NumberFormatException e) {
                response.put("status", "error");
                response.put("message", "无效的令牌时间戳");
                return ResponseEntity.status(401).body(response);
            }
            long now = System.currentTimeMillis();
            long validityMs = 7L * 24 * 60 * 60 * 1000; // 7天
            if (now - tokenTimestamp > validityMs) {
                response.put("status", "error");
                response.put("message", "令牌已过期");
                return ResponseEntity.status(401).body(response);
            }

            // 调用UserService验证令牌并获取用户信息
            User user = userService.getUserByToken(authToken);

            // 再次确认数据库中的令牌匹配
            if (user == null || user.getToken() == null || !user.getToken().equals(authToken)) {
                response.put("status", "error");
                response.put("message", "令牌无效");
                return ResponseEntity.status(401).body(response);
            }

            // 构造用户信息响应
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("realName", user.getRealName());
            userInfo.put("phoneNumber", user.getPhone());
            userInfo.put("role", "normal");

            // 构造成功响应
            response.put("status", "success");
            response.put("message", "获取用户信息成功");
            response.put("data", userInfo);

            // 返回200成功响应
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("status", "error");
            response.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.status(401).body(response);
        }
    }

    /**
     * 令牌解析校验接口
     * 从令牌中提取用户ID，在数据库中查找并对比签名
     */
    @PostMapping("/token/validate")
    public ResponseEntity<Map<String, Object>> validateToken(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取请求中的令牌
            String token = requestBody.get("token");
            
            // 验证令牌是否为空
            if (token == null || token.isEmpty()) {
                response.put("code", 3001);
                response.put("message", "令牌不能为空");
                return ResponseEntity.status(400).body(response);
            }

            // 从令牌中提取用户ID (格式: token_u10000_fa6d66791fd64b1598aee56f925b23eb_PX0xDL7xgNi2xSMJ_1758076557259)
            String[] tokenParts = token.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("code", 3001);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }

            // 提取用户ID
            String userIdStr = tokenParts[1].substring(1); // 移除前缀 'u'
            Long userId;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                response.put("code", 3001);
                response.put("message", "无效的用户ID格式");
                return ResponseEntity.status(400).body(response);
            }

            // 解析时间戳并校验是否过期（默认7天）
            long tokenTimestamp;
            try {
                tokenTimestamp = Long.parseLong(tokenParts[4]);
            } catch (NumberFormatException e) {
                response.put("code", 3001);
                response.put("message", "无效的令牌时间戳");
                return ResponseEntity.status(400).body(response);
            }
            long now = System.currentTimeMillis();
            long validityMs = 7L * 24 * 60 * 60 * 1000; // 7天
            if (now - tokenTimestamp > validityMs) {
                response.put("code", 3001);
                response.put("message", "令牌已过期");
                return ResponseEntity.status(401).body(response);
            }

            // 使用用户ID在数据库中查找用户
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                response.put("code", 3001);
                response.put("message", "用户不存在");
                return ResponseEntity.status(404).body(response);
            }

            // 对比令牌
            String storedToken = user.getToken();
            if (storedToken == null || !storedToken.equals(token)) {
                response.put("code", 3001);
                response.put("message", "令牌校验失败");
                return ResponseEntity.status(401).body(response);
            }

            // 校验通过，返回成功响应
            response.put("code", 3000);
            response.put("message", "令牌校验通过");
            response.put("username", user.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("code", 3001);
            response.put("message", "令牌校验异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}